问题描述(难度简单-160)
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
Example 1:
Example 2:
Example 3:
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
方法一:using hash
1 | package P160; |
方法二:using two pointer
双指针遍历,其中一个链表遍历到结尾之后从另一个链表的开头开始遍历,时间复杂度O(M+N),空间复杂度O(1)。
1 | package P160; |
总结
双指针的方式比较巧妙,注意需要在遍历到尾部的时候重新遍历另一个链表。